package com.example.pilipili.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.pilipili.common.R;
import com.example.pilipili.pojo.dto.UInfo;
import com.example.pilipili.pojo.entity.User;
import com.example.pilipili.dao.UserMapper;
import com.example.pilipili.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.pilipili.utils.MD5U;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liyv
 * @since 2023-12-01
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R register(User user) {
        // 查找账户是否重复
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("phone",user.getPhone()).or().eq("name",user.getName()) ;
        if(userMapper.exists(qw)) {
            return R.failed("该昵称已被占用或账户已被注册") ;
        }
        // MD5加密
        user.setPassword(MD5U.getMD5Password(user.getPassword()));
        user.setTime(LocalDate.now());
        userMapper.insert(user) ;
        user.setPassword(null);
        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<User> updateBaseInfo(User user) {
        User u = userMapper.selectById(user.getId()) ;
        if (u == null) {
            return R.failed("该用户不存在");
        }
         u.setName(user.getName() );
         u.setGender(user.getGender());
         u.setCardCase(user.getCardCase());
        userMapper.updateById(u) ;
        u.setPassword(null);
        return R.ok(u);
    }

    @Override
    public R<UInfo> selectInfoById(int uid) {

       return R.ok(userMapper.selectInfoById(uid)) ;
    }

    @Override
    public R<User> changeHandUrl(int uid ,String newUrl) {
        User u = userMapper.selectById(uid);
        u.setHandUrl(newUrl);
        userMapper.updateById(u) ;
        return R.ok(u);
    }

    @Override
    public R<List<User>> getsByStatus(int status) {
        QueryWrapper<User> qw = new QueryWrapper<>() ;
        qw.eq("status",status);
        return R.ok(userMapper.selectList(qw));
    }

    @Override
    public R<User> updateStatus(User user) {
       User u = userMapper.selectById(user.getId()) ;
       u.setStatus(user.getStatus());
       userMapper.updateById(u) ;
        return R.ok(u);
    }


}
